package com.hzw.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzw.api.ICommodityService;
import com.hzw.common.Constant;
import com.hzw.common.DateUtils;
import com.hzw.common.PageResult;
import com.hzw.dao.CommodityDao;
import com.hzw.dao.CommodityTypeDao;
import com.hzw.entity.Commodity;
import com.hzw.entity.CommodityType;
import com.hzw.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

@Service
public class CommodityService implements ICommodityService {
    @Autowired
    CommodityDao commodityDao;

    @Autowired
    CommodityTypeDao commodityTypeDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(Commodity commodity) {
        commodity.setId(UUID.randomUUID().toString().replace("-", ""));
        if (StringUtils.isEmpty(commodity.getIsShow())) {
            commodity.setIsShow(1);
        }
        this.getClassificationId(commodity);
        //处理餐品图片信息
        //拼接输入流路径
        if (!StringUtils.isEmpty(commodity.getImg()) && !commodity.getImg().contains("images/commodity/")) {
            String impFilePath = Constant.FILE_IMP_PATH + commodity.getImg();
            String filePath = this.FileCopy(impFilePath);
            commodity.setImg(filePath);
        }
        return commodityDao.insert(commodity);
    }

    @Override
    public void delById(Commodity commodity) {
        commodityDao.delById(commodity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Commodity commodity) {
        //当图片为空将原先图片地址估值过来
        Commodity oldCommodity = new Commodity();
        if (StringUtils.isEmpty(commodity.getImg())) {
            oldCommodity.setId(commodity.getId());
            List<Commodity> select = this.select(oldCommodity);
            commodity.setImg(select.get(0).getImg());
        }
        this.delById(commodity);
        this.insert(commodity);
    }

    @Override
    public List<Commodity> select(Commodity commodity) {
        return commodityDao.select(commodity);
    }

    @Override
    public PageResult<Commodity> pageSelect(Commodity commodity) {
        PageInfo<User> pageInfo = PageHelper.startPage(commodity.getPageNum(), commodity.getPageSize())
                .doSelectPageInfo(() -> {
                    commodityDao.select(commodity);
                });
        PageResult pageResult = new PageResult().setTotal(pageInfo.getTotal()).setResult(pageInfo.getList());
        return pageResult;
    }

    /**
     * 根据分类名称获取分类id
     *
     * @param commodity
     * @return
     */
    private Commodity getClassificationId(Commodity commodity) {

        commodity.setCreateTime(DateUtils.getNowTime());
        //通过分类名称获取分类ID
        CommodityType commodityType = new CommodityType();
        commodityType.setClassification(commodity.getClassification());
        List<CommodityType> typeResList = commodityTypeDao.select(commodityType);
        if (!CollectionUtils.isEmpty(typeResList)) {
            commodity.setClassificationId(typeResList.get(0).getId());
        }
        return commodity;
    }

    /**
     * 文件上传
     *
     * @param filePath
     */
    @Override
    public String FileCopy(String filePath) {
        File sourceFile = new File(filePath);
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".png";
        File destFile = new File(Constant.FILE_PATH + fileName);
        try {
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(destFile);
            // 定义缓冲区
            byte[] buffer = new byte[1024];
            int data;
            while ((data = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Constant.FILE_PATH_HTML + fileName;
    }

    /**
     * 根据商品名称获取图片信息
     *
     * @param commodityName
     * @return
     */
    public String getImg(String commodityName) {
        Commodity commodity = new Commodity();
        commodity.setCommodityName(commodityName);
        List<Commodity> select = commodityDao.select(commodity);
        return select.get(0).getImg();
    }

    /**
     * 根据商品名称获取商品ID
     *
     * @param commodityName
     * @return
     */
    public String getCommodityId(String commodityName) {
        Commodity commodity = new Commodity();
        commodity.setCommodityName(commodityName);
        List<Commodity> select = commodityDao.select(commodity);
        return select.get(0).getId();
    }

    /**
     * 根据商品名称获取商品价格
     *
     * @param commodityName
     * @return
     */
    public double getPrice(String commodityName) {
        Commodity commodity = new Commodity();
        commodity.setCommodityName(commodityName);
        List<Commodity> select = commodityDao.select(commodity);
        return select.get(0).getPrice();
    }

    /**
     * 根据商品名称获取分类
     *
     * @param commodityName
     * @return
     */
    public String getType(String commodityName) {
        Commodity commodity = new Commodity();
        commodity.setCommodityName(commodityName);
        List<Commodity> select = commodityDao.select(commodity);
        String classification = select.get(0).getClassification();
        return classification;
    }

    /**
     * 添加购物车时减少库存（库存为0时自动下架）
     *
     * @param commodityName
     * @return
     */
    public void changeStock(String commodityName, Integer num) {
        Commodity commodity = new Commodity();
        commodity.setCommodityName(commodityName);
        List<Commodity> select = commodityDao.select(commodity);
        int stock = Integer.valueOf(select.get(0).getStock()).intValue();
        stock = stock - num;
        commodity.setStock(String.valueOf(stock));
        //当库存为0时自动下架
        if (stock <= 0) {
            commodity.setIsShow(1);
            commodity.setStock("0");
        }
        String commodityId = this.getCommodityId(commodityName);
        commodity.setId(commodityId);
        commodityDao.updateById(commodity);
    }
}
